package personal.wang.juc.completableFuture;


import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * @className: CompletableFutureTest
 * @Description:
 * @Author: wangyifei
 * @Date: 2025/3/6 15:19
 */
public class CompletableFutureTest {
    public static void main(String[] args) throws IOException, InterruptedException {
        // 消费者单条的粒度拉取数据，然后单线程消费：
        // 1、去redis查询缓存
        // 2、封装字段
        // 3、入数据库
        //4、本条消费成功，提交offset
        CompletableFuture<Boolean> handle = CompletableFuture.supplyAsync(() -> {
            // redis 里面查询
            System.out.println("redis 里面查询");
            int i = 1/0;
            return "redis result";
        }).handle((r, t) -> {
            if (Objects.nonNull(t)) {
                System.out.println("封装字段 cancel");
                return "cancal";
            }
            // 封装字段
            System.out.println("封装字段");
            return "handle " + r;
        }).handle((r, t) -> {
            if (Objects.nonNull(t) || "cancel".equals(r)) {
                System.out.println("insert cancel");
                return "cancal";
            }
            try {
                // do insert
                int i = 1 / 0;
                System.out.println("do insert");
            } catch (Exception e) {
                // rollup
                System.out.println("do rollup");
                return "cancel";
            } finally {
                // close some
            }
            return "insert db " + r;
        }).handle((r, t) -> {
            if (Objects.nonNull(t) || "cancel".equals(r)) {
                System.out.println("consumer cancel");
                return false;
            }
            try {
                // consumer msg
                System.out.println("consumer msg and insert something");
                // commit
                System.out.println("commit");
            } catch (Exception e) {
                System.out.println("db rollup");
                return false;
            } finally {
                // close some
            }
            return true;
        });
        Boolean join = handle.join();
        System.out.println(join);
    }
}
